<template>
        <div style="width: 100%;height: 100%;display: flex">
            <vue-advanced-chat style="width: 100%"
                height="calc(90vh - 20px)"
                :current-user-id="currentUserId"
                :rooms="JSON.stringify(rooms)"
                :messages="messageStr"
                :loading-rooms="loadingRooms"
                show-audio="false"
                show-add-room="false"
                room-info-enabled="true"
                @menu-action-handler="roomHandler($event.detail[0])"
                @room-action-handler="roomHandler($event.detail[0])"
                :rooms-loaded="roomsLoaded"
                :messages-loaded="messagesLoaded"
                :scroll-distance="200"
                @fetch-more-rooms="fetchMoreRooms"
                @send-message="sendMessage($event.detail[0])"
                @fetch-messages="fetchMessages($event.detail[0])"
                :menu-actions="JSON.stringify(roomActions)"
                text-messages='{"ROOMS_EMPTY": "对话列表为空","ROOM_EMPTY": "房间为空",
                "NEW_MESSAGES": "新消息","MESSAGE_DELETED": "消息已删除","MESSAGES_EMPTY": "暂无消息",
                "CONVERSATION_STARTED": "最早消息","TYPE_MESSAGE": "请输入内容",
                "SEARCH": "查询","IS_ONLINE": "是否在线","LAST_SEEN": "最后查看",
                "IS_TYPING": "正在输入中...","CANCEL_SELECT_MESSAGE": "取消"}'
            />
            <div class="card" v-show="showDetail">
                <el-form label-position="left" label-width="80px" :model="formData" >
                    <el-form-item label="游戏区服" prop="gameServer">
                        <el-input disabled v-model="formData.gameServer" auto-complete="off">
                        </el-input>
                    </el-form-item>
                    <el-form-item label="商品信息" prop="remark">
                        <el-input disabled v-model="formData.itemDesc" type="textarea"  show-word-limit maxlength="200" auto-complete="off" ></el-input>
                    </el-form-item>
                    <el-form-item label="下单时间" prop="amount">
                        <el-input disabled v-model="formData.createTime" auto-complete="off">
                        </el-input>
                    </el-form-item>
                    <el-form-item label="订单状态" prop="auction">
                        <el-input disabled :value="statusMap[formData.status]" auto-complete="off">
                        </el-input>
                    </el-form-item>
                    <el-form-item label="支付状态" prop="auction">
                        <el-input disabled :value="formData.paymentStatus === 1
                         ? '已支付' : '未支付'" auto-complete="off">
                        </el-input>
                    </el-form-item>
                    <el-form-item label="支付类型" prop="auction">
                        <el-input disabled :value="formData.paymentMethod === '0'
                         ? '支付宝' : formData.paymentMethod === '1' ? '微信':'其他'" auto-complete="off">
                        </el-input>
                    </el-form-item>
                    <el-form-item label="订单类型" prop="charge">
                        <el-input disabled :value="[3,15].includes(formData.type) ?
                        '出售给商城' : '正常订单'" auto-complete="off">
                        </el-input>
                    </el-form-item>
                    <el-form-item label="订单金额" prop="charge">
                        <el-input disabled :value="formData.totalAmount" auto-complete="off">
                            <template slot="append">元</template>
                        </el-input>
                    </el-form-item>
                    <el-form-item label="联系电话" prop="remark">
                        <el-input disabled v-model="formData.phone" type="textarea"  show-word-limit maxlength="200" auto-complete="off" ></el-input>
                    </el-form-item>
                </el-form>
            </div>
        </div>
</template>
<script>
import store from "@/store";
import { register } from 'vue-advanced-chat'
import axios from "@/utils/axios";
register()
export default {
    name: 'app',
    data() {
        return {
            statusMap:{
                '0': '未发货',
                '1': '订单完成',
                '2': '订单取消',
                '3': '卖家已接单',
                '4': '订单删除',
                '5': '卖家已发货'
            },
            i18n: "{" +
                "ROOMS_EMPTY: '对话列表为空'," +
                "ROOM_EMPTY: '用户为空','NEW_MESSAGES': '新消息'," +
                "MESSAGE_DELETED: '消息已删除'," +
                "MESSAGES_EMPTY: '消息为空'," +
                "IS_ONLINE: '是否在线'," +
                "LAST_SEEN: '最后时间'," +
                "IS_TYPING: '用户输入中...'," +
                "CANCEL_SELECT_MESSAGE: '取消选择'" +
                "SEARCH: ''"+
                "}",
            timer: '',
            formData:{},
            socket: '',
            roomStr: '',
            currentUserId: 'admin',
            rooms: [],
            messages: [],
            roomsLoaded: false,
            loadingRooms: true,
            selectedRoomId: '',
            page: 1,
            messagesLoaded: false,
            messagePage: 1,
            messageStr: [],
            showDetail: false,
            roomActions: [
                // { name: 'inviteUser', title: 'Invite User' },
                // { name: 'removeUser', title: 'Remove User' },
                // { name: 'deleteRoom', title: 'Delete Room' }
            ],
            orderActions: [
                { name: 'detail', title: '订单详情' },
                { name: 'take', title: '商家接单' },
                { name: 'send', title: '订单发货' },
                { name: 'receive', title: '确认收货' },
                // { name: 'completed', title: '订单完成' },
            ]
        }
    },
    watch:{
        'formData.status': {
            deep: true,
            immediate: true,
            handler(val){
                // '0': '未发货',
                //     '1': '订单完成',
                //     '2': '订单取消',
                //     '3': '卖家已接单',
                //     '4': '订单删除',
                //     '5': '卖家已发货'
                let isBuy = [3,15].includes(this.formData.type)  ;
                switch (val) {
                    case 0:
                        if (isBuy){
                            this.roomActions = [
                                { name: 'detail', title: '订单详情' },
                            ]
                        }else{
                            this.roomActions = [
                                { name: 'detail', title: '订单详情' },
                                { name: 'take', title: '商家接单' },
                                { name: 'send', title: '订单发货' },
                            ]
                        }
                        break;

                    case 3:
                        if (isBuy){
                            this.roomActions = [
                                { name: 'detail', title: '订单详情' },
                            ]
                        }else{
                            this.roomActions = [
                                { name: 'detail', title: '订单详情' },
                                { name: 'send', title: '订单发货' },
                            ]

                        }

                        break;
                    case 5:
                        if (isBuy){
                            this.roomActions = [
                                { name: 'detail', title: '订单详情' },
                                { name: 'receive', title: '确认收货' }
                            ]
                        }else{
                            this.roomActions = [
                                { name: 'detail', title: '订单详情' },
                            ]
                        }
                        break;
                    case 4:
                    case 2:
                    case 1:
                        this.roomActions = [
                            { name: 'detail', title: '订单详情' },
                        ]
                        break;
                    // { name: 'detail', title: '订单详情' },
                    // { name: 'take', title: '商家接单' },
                    // { name: 'send', title: '订单发货' },
                    // { name: 'receive', title: '确认收货' },
                }



            }
        }
    },
    mounted() {
        // this.initWs()
        this.$EventBus.$on("newMessage",(data)=>{
            var json = JSON.parse(data);
            const index = this.rooms.findIndex(r => r.roomId == json.groupId); // 找到对象索引

            if (index !== -1) { // 如果找到了
                const [movedRoom] = this.rooms.splice(index, 1); // 移除该对象
                movedRoom.unreadCount = movedRoom.unreadCount+1
                this.rooms.unshift(movedRoom); // 将其添加到数组最前面
            }else{
                this.rooms.unshift({
                    roomId: json.groupId,
                    unreadCount: 1,
                    roomName: json.groupId.indexOf('user-') > -1 ? '用户-'+json.groupId : '订单-'+json.groupId,
                    avatar: json.groupId.indexOf('user-') > -1  ? 'http://8.136.119.108/file/user.png' : 'http://8.136.119.108/file/order.png',
                    users:[
                        // { _id: o.userId, username: o.userName },
                        // { _id: '客服', username: '客服'}
                    ],
                })
            }
        })
        this.fetchRoom();
        // this.timer = setInterval(()=>{
        //     this.rooms = []
        //     this.fetchRoom()
        // },5000)
    },
    beforeDestroy() {
        clearInterval(this.timer)
    },
    methods: {
        completedOrder(orderId){
            axios({
                url: "/admin/dnf/order/completed",
                method: "post",
                data: {
                    id: orderId,
                }
            }).then(res=>{
                if (res.code == 1){
                    this.$message.error(res.message)
                }
            })

        },
        orderDetail(id){
            axios({
                url: "/admin/dnf/order/"+id,
                method: "get",
            }).then(res=>{
                console.log("===========>",res)
                this.formData = {...res.data};
                this.showDetail = true
                if ([3,15].includes(this.formData.type) && this.formData.status == 0){
                    this.takeOrder(this.formData.id )
                }
            })
        },
        receive(orderId){
            axios({
                url: "/admin/dnf/order/confirmReceive",
                method: "post",
                data: {
                    id: orderId,
                }
            }).then(res=>{
                if (res.code == 1){
                    this.$message.error(res.message)
                }
                this.formData.status = 1;
            })
        },
        sendOrder(orderId){
            axios({
                url: "/admin/dnf/order/send",
                method: "post",
                data: {
                    id: orderId,
                }
            }).then(res=>{
                if (res.code == 1){
                    this.$message.error(res.message)
                }
                this.formData.status = 5;
            })
        },
        takeOrder(orderId){
            axios({
                url: "/admin/dnf/order/take",
                method: "post",
                data: {
                    id: orderId,
                }
            }).then(res=>{
                if (res.code == 1){
                    this.$message.error(res.message)
                }
                this.formData.status = 3;
                // let obj = {
                //     sender_id: '客服',
                //     groupId: this.orderId,
                //     from: '客服',
                //     createTime: new Date().getTime(),
                //     cmd: 11,
                //     chatType: "1",
                //     msgType: "0",
                //     content: "商家已接单"
                // }
                // this.socket.send(JSON.stringify(obj));
            })
        },
        roomHandler({ action, roomId }) {
            switch (action.name) {
                case 'take':
                    this.takeOrder(roomId);
                    return
                case 'completed':
                    this.completedOrder(roomId);
                    return
                case 'send':
                    this.sendOrder(roomId);
                    return
                case 'receive':
                    this.receive(roomId);
                    return
                case 'detail':
                    this.orderDetail(roomId);
                    return
            }
        },
        fetchMoreRooms() {
            let thiz = this;
            this.messagesLoaded = false
             this.page = this.page + 1
             this.roomsLoaded = false
             axios({
                 url: "/admin/dnf/order/listOnlineUser",
                 method: "post",
                 params: {
                     page: this.page,
                     limit: 10
                 }
             }).then(response => {
                 // {
                 //     roomId: '1',
                 //         roomName: 'Room 1',
                 //     avatar: 'https://th.bing.com/th/id/OIP.DQsvT1ADHVHD19CpcLkEtQHaHa?w=165&h=180&c=7&r=0&o=5&pid=1.7',
                 //     users: [
                 // ]
                 if (!response.data || response.data.length == 0){

                     this.roomsLoaded = true
                     return ;
                 }
                 response.data.forEach(o=>{
                     let msg = {
                         unreadCount: o.messages,
                         roomId: o.groupId,
                         roomName: o.name,
                         avatar: o.name.indexOf("用户") > -1 ? 'http://8.136.119.108/file/user.png' : 'http://8.136.119.108/file/order.png',
                         users:[
                             // { _id: o.userId, username: o.userName },
                             // { _id: '客服', username: '客服'}
                         ],
                     };
                     if (o.lastMessage){
                         msg.lastMessage={
                             _id: o.lastMessage.id,
                             content: o.lastMessage.content.startsWith("_imgUrl://")?"[图片]":o.lastMessage.content,
                             senderId: o.lastMessage.from,
                             username: o.lastMessage.from,
                             from: o.lastMessage.from,
                             timestamp: thiz.parseTimestamp(o.lastMessage.createTime, 'HH:mm:ss'),
                             date: thiz.parseTimestamp(o.lastMessage.createTime, 'DD MMMM YYYY'),
                         }
                     }
                     this.rooms.push(msg)
                 })
                 this.roomsLoaded = false
                 this.messagesLoaded = true
             })
        },
        fetchRoom(){
            let thiz = this
            axios({
                url: "/admin/dnf/order/listOnlineUser",
                method: "post",
                params: {
                    page: this.page,
                    limit: 10
                }
            }).then(response => {
                    // {
                    //     roomId: '1',
                    //         roomName: 'Room 1',
                    //     avatar: 'https://th.bing.com/th/id/OIP.DQsvT1ADHVHD19CpcLkEtQHaHa?w=165&h=180&c=7&r=0&o=5&pid=1.7',
                    //     users: [
                    // ]
                if (!response.data || response.data.length == 0){

                    this.roomsLoaded = true
                    return ;
                }
                response.data.forEach(o=>{
                    let msg ={
                        roomId: o.groupId,
                        unreadCount: o.messages,
                        roomName: o.name,
                        avatar: o.name.indexOf("用户") > -1 ? 'http://8.136.119.108/file/user.png' : 'http://8.136.119.108/file/order.png',
                        users:[
                            // { _id: o.userId, username: o.userName }
                        ]
                    }
                    if (o.lastMessage){
                        msg.lastMessage={
                            _id: o.lastMessage.id,
                            content: o.lastMessage.content.startsWith("_imgUrl://")?"[图片]":o.lastMessage.content,
                            senderId: o.lastMessage.from,
                            username: o.lastMessage.from,
                            from: o.lastMessage.from,
                            timestamp: thiz.parseTimestamp(o.lastMessage.createTime, 'HH:mm:ss'),
                            date: thiz.parseTimestamp(o.lastMessage.createTime, 'DD MMMM YYYY'),
                        }
                    }
                    this.rooms.push(msg)
                })
                this.roomStr = JSON.stringify(this.rooms)
                this.roomsLoaded = false
                this.loadingRooms = false
            })
        },
        initWs(groupId){
            let thiz = this;
            let socket = new WebSocket("ws://8.136.119.108:8888?token="+store.getters.token+"&username=web");

            this.socket = socket;
            socket.onopen = function(e){
                thiz.socket.send(JSON.stringify({cmd: 7,groupId: groupId}))

            };
            socket.onerror = function(e){
                // logDiv.innerHTML+="<font color='red' size='1'>异常:"+e+"</font><br>";
                // scrollToBottom();
            };
            socket.onclose = function(e){
                // logDiv.innerHTML+="<font color='green' size='1'>关闭连接...</font><br>";
                // document.getElementById("onlinePanel").innerHTML="&nbsp;在线成员(0/0)";
                // scrollToBottom();
            };
            socket.onmessage = function(e){
                var data = e.data;
                var dataObj = eval("("+data+")");//转换为json对象\
                if(dataObj.command == 11){
                    let msg = {
                        //{"chatType":1,"cmd":11,"content":"111","createTime":1733761169977,
                        // "groupId":"10","id":"b1d8257fc8e240c2a6d308cd035e5650","msgType":0}
                        _id: dataObj.data.id,
                        content: dataObj.data.content,
                        senderId: dataObj.data.from,
                        username: dataObj.data.from,
                        from: dataObj.from,
                        timestamp: thiz.parseTimestamp(dataObj.data.createTime, 'HH:mm:ss'),
                        date: thiz.parseTimestamp(dataObj.data.createTime, 'DD MMMM YYYY'),
                    }
                    if (!dataObj.data.content){
                        if (dataObj.data.cmd == 21){
                            thiz.formData.status = 5
                        }
                        return
                    }

                    if (dataObj.data.content.startsWith("_imgUrl://")){
                        msg.files=[{
                            name: '图片',
                            size: '',
                            type: 'png',
                            duration: 14.4,
                            url: dataObj.data.content.substr(10),
                            preview: dataObj.data.content.substr(10)
                        }]
                        msg.content = ''
                    }
                    thiz.messages.push(msg)
                    thiz.messageStr = JSON.stringify(thiz.messages)
                }
                // //接收到聊天响应处理;
                //     COMMAND_CHAT_RESP(dataObj);
                // }else if(dataObj.command == 18){//获取用户信息响应处理;
                //     COMMAND_GET_USER_RESP(dataObj);
                // }else if(10000 == dataObj.code && dataObj.command == 12){//聊天发送状态;
                //     COMMAND_CHAT_RESP_SEND_STATUS(data);
                // }else if(dataObj.command == 9){//加入群组的消息通知处理;
                //     COMMAND_JOIN_GROUP_NOTIFY_RESP(dataObj);
                // }else if(dataObj.command == 10){
                //     COMMAND_EXIT_GROUP_NOTIFY_RESP(dataObj);
                // }else if(dataObj.command == 20 && dataObj.code == 10015){
                //     //获取消息失败，未开启持久化处理
                //     //...
                // }else if(dataObj.command == 20 && dataObj.code == 10016){//处理离线消息;
                //     var msgFlag = "离线消息";
                //     COMMAND_GET_MESSAGE_RESP(dataObj,msgFlag);
                // }else if(dataObj.command == 20 && dataObj.code == 10018){//处理历史消息;
                //     var msgFlag = "历史消息";
                //     var msgObj = dataObj.data;
                //     if(msgObj){
                //         COMMAND_GET_MESSAGE_RESP(dataObj,msgFlag);
                //     }else{//没有历史消息;
                //         OTHER(data);
                //     }
                // }else if(dataObj.command == 6){//登陆命令返回状态处理
                //     COMMAND_LOGIN_RESP(dataObj,data);
                // }else{
                //     OTHER(data);
                // }
                // scrollToBottom();
                console.log(e)
            };
        },
        async fetchMessages({ room, options = {} }) {
            console.log("fetch===>{},{}",room, options)
            if (options.reset) {
                this.joinGroup(room.roomId)
                this.resetMessages()
                this.messagePage = 1;
                this.showDetail = false
                if (room.roomName.indexOf("订单") > -1){
                    this.roomActions = [...this.orderActions]
                    this.orderDetail(room.roomId);
                }else{
                    this.roomActions = []
                }
            }
            room.unreadCount = 0;
            this.messagesLoaded=false
            const response = await axios({
                url: "/admin/dnf/order/fetchMessage",
                method: "post",
                params: {
                    roomId: room.roomId,
                    userId: 'admin',
                    page: this.messagePage
                }
            })
            if (response.data && response.data.length >0 ){
                let msgs = [];
                response.data.forEach(o=>{
                    let msg = {
                            "_id": o.id,
                            "content": o.content,
                            "senderId": o.from,
                            "username": o.from,
                            timestamp: this.parseTimestamp(o.createTime, 'HH:mm:ss'),
                            date: this.parseTimestamp(o.createTime, 'DD MMMM YYYY'),
                        }
                    if (!o.content){
                        return
                    }
                    if (o.content && o.content.startsWith("_imgUrl://")){
                        msg.files=[{
                            name: '图片',
                            size: '',
                            type: 'png',
                            duration: 14.4,
                            url: o.content.substr(10),
                            preview: o.content.substr(10)
                        }]
                        msg.content = ''
                    }
                    msgs.push(
                        msg
                    )
                })
                this.messages = msgs.concat(this.messages)
                this.messageStr = JSON.stringify(this.messages)
                this.messagesLoaded=false
                this.messagePage++
            }else{
                this.messagesLoaded = true;
            }
            // do fetchMessage
        },
        resetMessages() {
            this.messages = []
            this.messageStr = JSON.stringify(this.messages)
            // this.messagesLoaded = false
            // this.lastLoadedMessage = null
            // this.previousLastLoadedMessage = null
            // this.listeners.forEach(listener => listener())
            // this.listeners = []
        },
        zeroPad (num, pad)  {
            return String(num).padStart(pad, '0')
        },
        isSameDay(d1, d2){
            return (
                d1.getFullYear() === d2.getFullYear() &&
                d1.getMonth() === d2.getMonth() &&
                d1.getDate() === d2.getDate()
            )
        },
        joinGroup(groupId){
             if (this.selectedRoomId){
                 this.socket.send(JSON.stringify({cmd: 14,groupId: this.selectedRoomId}))
             }
             this.selectedRoomId = groupId
            this.initWs(this.selectedRoomId)
        },
        sendMessage ({ content, roomId, files, replyMessage }) {
            let thiz = this
            if (content){
                let obj = {
                    sender_id: 'admin',
                    groupId: roomId,
                    from: 'admin',
                    createTime: new Date().getTime(),
                    cmd: 11,
                    chatType: "1",
                    msgType: "0",
                    content: content,
                    extras:{
                        username: '商家'
                    }
                }
                thiz.socket.send(JSON.stringify(obj));
            }
            if (files){
                files.forEach(async f=>{
                    const formData = new FormData();
                    formData.append("file", f.blob)
                    const response = await axios.post("/admin/file/upload",
                        formData, {
                            headers: {
                                'Content-Type': 'multipart/form-data'
                            }
                        }
                    )
                    console.log(response)
                    // reader.readAsDataURL(f.blob)
                    // reader.onload = function () {
                    //     const base64Data = reader.result;
                    if (response.code != 500 && response.data){
                        let obj = {
                            sender_id: 'admin',
                            groupId: roomId,
                            from: 'admin',
                            createTime: new Date().getTime(),
                            cmd: 11,
                            chatType: "1",
                            msgType: "0",
                            content: "_imgUrl://" + response.data,
                            extras:{
                                username: '商家'
                            }
                        }
                        thiz.socket.send(JSON.stringify(obj));
                    }
                    // };

                })
            }
            // if (text.length > 0) {
            //     this.newMessagesCount = this.isChatOpen ? this.newMessagesCount : this.newMessagesCount + 1
            //     this.onMessageWasSent({ author: 'support', type: 'text', data: { text } })
            // }
        },
        onMessageWasSent (message) {
            // called when the user sends a message
            this.messageList = [ ...this.messageList, message ]
        },
        openChat () {
            // called when the user clicks on the fab button to open the chat
            this.isChatOpen = true
            this.newMessagesCount = 0
        },
        closeChat () {
            // called when the user clicks on the botton to close the chat
            this.isChatOpen = false
        },
        handleScrollToTop () {
            // called when the user scrolls message list to top
            // leverage pagination for loading another page of messages
        },
        handleOnType () {
            console.log('Emit typing event')
        },
        editMessage(message){
            const m = this.messageList.find(m=>m.id === message.id);
            m.isEdited = true;
            m.data.text = message.data.text;
        },
        parseTimestamp (timestamp, format = ''){
            if (!timestamp) return

            const date = new Date(timestamp )

            if (format === 'HH:mm:ss') {
                return `${this.zeroPad(date.getHours(), 2)}:${this.zeroPad(date.getMinutes(), 2)}:${this.zeroPad(date.getSeconds(), 2)}`
            } else if (format === 'DD MMMM YYYY') {
                const options = { month: 'long', year: 'numeric', day: 'numeric' }
                return `${new Intl.DateTimeFormat('zh', options).format(date)}`
            } else if (format === 'DD/MM/YY') {
                const options = { month: 'numeric', year: 'numeric', day: 'numeric' }
                return `${new Intl.DateTimeFormat('zh', options).format(date)}`
            } else if (format === 'DD MMMM, HH:mm') {
                const options = { month: 'long', day: 'numeric' }
                return `${new Intl.DateTimeFormat('zh', options).format(
                    date
                )}, ${this.zeroPad(date.getHours(), 2)}:${this.zeroPad(date.getMinutes(), 2)}`
            }

            return date
        }
    }
}
</script>
<style>
.card{
    width: 30%;
    padding:20px;
    margin-left: 10px;
    border: 1px solid #ddd;
    border-radius: 8px;
    box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
}
</style>
